package com.example.courseselectionsystemconsume.timerTasks.service;

import com.example.courseselectionsystemconsume.timerTasks.Timer1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

/**
 * @description: TODO
 * @author: Tokyo_God
 * @date: 2021/1/9 20:29
 * Role of:
 * @version: v1.0
 */
@Component
public class Timer1Service {
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Autowired
    private Timer1 timer1;

    private ScheduledFuture<?> future;



    //开启  定时器 (定时器会在10秒后开启)
    public void startCron() {
        System.out.println("正在开启定时器1--------------------------------------------");
        //给上面的  赋值  参数（定时器类，Trigger）    声明到局部好关闭
        future = threadPoolTaskScheduler.schedule(timer1, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                return new CronTrigger("0/10 * * * * ?").nextExecutionTime(triggerContext);
            }
        });
        /*System.out.println("DynamicTask.startCron1()");*/
    }

    //关闭定时器
    public void stopCron() {
        System.out.println("正在关闭定时器1--------------------------------------------");
        //如果定时器不是null
        if (future != null) {
            future.cancel(true);
        }
        /*System.out.println("DynamicTask.stopCron1()");*/
    }

    //判断当前定时器是否关闭
    public boolean isClose(){
        if (future != null&&!future.isCancelled()) {
            return false;
        }
        return true;
    }
}
